<template>
  <div>
    <div class="mu_box">
      <el-form
        class="multiple_form"
        label-position="top"
        :model="form"
        ref="formName"
        :rules="rules"
        :inline="false"
        size="normal"
      >
        <el-form-item label="应用程序名称" prop="siddhiAppName">
          <el-select
            class="w100"
            size="small"
            filterable
            v-model="form.siddhiAppName"
            placeholder="请选择"
          >
            <el-option
              v-for="item in listSiddhiApps"
              :key="item.siddhiAppName"
              :label="item.siddhiAppName"
              :value="item.siddhiAppName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流名称" prop="streamName">
          <el-select
            class="w100"
            size="small"
            placeholder="请选择一个流"
            filterable
            v-model="form.streamName"
            @change="streamSele"
          >
            <el-option
              v-for="item in form.listStreams"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据源" prop="dataSourceLocation">
          <el-input
            v-model="form.dataSourceLocation"
            placeholder="请输入"
            size="small"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="驱动程序类" prop="driver">
          <el-input
            v-model="form.driver"
            placeholder="请输入"
            size="small"
            clearable
          ></el-input>
        </el-form-item>
        <div class="user_paw">
          <el-form-item
            class="w100"
            style="margin-right: 10px"
            label="用户名"
            prop="username"
          >
            <el-input
              v-model="form.username"
              placeholder="请输入"
              size="small"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item class="w100" label="密码" prop="password">
            <el-input
              show-password
              v-model="form.password"
              placeholder="请输入"
              size="small"
              clearable
            ></el-input>
          </el-form-item>
        </div>
        <div class="connect_msg">
          <el-button
            style="margin-right: 10px"
            :loading="btnLoading"
            size="small"
            type="primary"
            @click="handleConnect"
            >连接到数据库</el-button
          >
          <span v-html="databaseMsg" v-if="databaseMsg"></span>
        </div>

        <el-form-item label="表名" prop="tableName">
          <el-select
            class="w100"
            size="small"
            filterable
            v-model="form.tableName"
            placeholder="请选择"
          >
            <el-option
              v-for="item in tabNames"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <div class="user_paw">
          <el-form-item
            class="w100"
            style="margin-right: 10px"
            label="时间戳属性"
            prop="timestampAttribute"
          >
            <el-radio
              slot="label"
              v-model="form.isTimestampInterval"
              :label="false"
              >时间戳属性</el-radio
            >
            <el-select
              class="w100"
              size="small"
              placeholder="请选择"
              v-model="form.timestampAttribute"
              :disabled="
                attributesTypeSele.length == 0 || form.isTimestampInterval
              "
            >
              <el-option
                v-for="item in attributesTypeSele"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            class="w100"
            label="时间戳间隔"
            prop="timestampInterval"
          >
            <el-radio
              slot="label"
              v-model="form.isTimestampInterval"
              :label="true"
              >时间戳间隔</el-radio
            >
            <el-input
              :disabled="!form.isTimestampInterval"
              v-model="form.timestampInterval"
              placeholder="请输入"
              size="small"
              clearable
            ></el-input>
          </el-form-item>
        </div>
        <div v-if="form.listAttributes.length !== 0">
          <el-form-item v-for="li in form.listAttributes" :key="li.name">
            <div slot="label">{{ li.name }} ({{ li.type[0] }})</div>
            <el-select
              class="w100"
              size="small"
              placeholder="请选择"
              v-model="li.attributesType"
              :disabled="attributesTypeSele.length == 0"
            >
              <el-option
                v-for="item in attributesTypeSele"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option> </el-select
          ></el-form-item>
        </div>
      </el-form>
    </div>
    <div class="btns">
      <el-button size="small" v-if="isDel" @click="handleDel">删除</el-button>
      <el-button size="small" type="primary" @click="onSubmit">完成</el-button>
    </div>
  </div>
</template>

<script>
import Datepicker from "@/components/Datepicker";
import { mapGetters } from "vuex";
import _ from "lodash";
import {
  listStreams,
  listAttributes,
  connectToDatabase,
  retrieveTableNames,
  retrieveColumnNames,
} from "@/api/siddhi";

export default {
  components: {
    Datepicker,
  },
  computed: {
    ...mapGetters(["listSiddhiApps"]),
  },
  props: {
    AnalogSourceObj: {
      type: Array,
      default: () => [],
    },
    index: {
      type: Number,
      default: null,
    },
  },
  watch: {
    // 应用程序下拉框选择或者赋值之后触发
    "form.siddhiAppName"(val) {
      if (val) {
        const obj = this.AnalogSourceObj.find(
          (i2) =>
            i2.siddhiAppName == val &&
            i2.simulationType == "DATABASE_SIMULATION"
        );
        // 存在直接回显,不存在的 置空
        if (obj) {
          this.isDel = true;
          // this.form.listAttributes = obj.listAttributes;
          // 找到的话深拷贝在赋值,不然下拉框会同步修改父节点属性
          this.form = _.cloneDeep(obj);
        } else {
          this.isDel = false;
          this.form.listAttributes = [];
          // this.form.streamName = "";
          this.$set(this.form, "streamName", "");
        }

        // this.form.listStreams = [];

        this.siddhiSele(val);
      }
    },
    "form.tableName"(val) {
      // this.retrieveTableNames()
      if (val) {
        this.changeTabName(val);
      }
    },
  },
  mounted() {},
  data() {
    return {
      tabNames: [],
      databaseMsg: "",
      btnLoading: false,
      attributesTypeSele: [],
      rules: {
        siddhiAppName: [{ required: true, message: "请选择应用程序" }],
        streamName: [{ required: true, message: "请选择流" }],
        driver: [{ required: true, message: "请输入驱动程序类" }],
        password: [{ required: true, message: "请输入密码" }],
        username: [{ required: true, message: "请输入用户名" }],
        dataSourceLocation: [{ required: true, message: "请输入数据源" }],
        tableName: [{ required: true, message: "请选择表" }],
      },
      isDel: false,
      form: {
        isTimestampInterval: false,
        timestampAttribute: "",
        timestampInterval: "",
        driver: "com.mysql.jdbc.Driver",
        username: "root",
        password: "rootiot123",
        dataSourceLocation:
          'jdbc:mysql://223.223.176.32:30716/ss?autoReconnect=true&useSSL=false',
        siddhiAppName: "",
        tableName: "",
        streamName: "",
        listAttributes: [],
        timestampInterval: "",
        listStreams: [],
        simulationType: "DATABASE_SIMULATION", //类型===随机的 cvg 数据库
      },
    };
  },
  methods: {
    changeTabName(val) {
      retrieveColumnNames(this.form, val).then((res) => {
        console.log(res, "获取表下的字段");
        this.attributesTypeSele = res.data;
      });
    },
    handleConnect() {
      if (!this.form.dataSourceLocation) {
        this.$msg("请输入数据源");
        return;
      }
      if (!this.form.driver) {
        this.$msg("请输入驱动程序类");
        return;
      }
      if (!this.form.username) {
        this.$msg("请输入用户名");
        return;
      }
      if (!this.form.password) {
        this.$msg("请输入密码");
        return;
      }
      this.btnLoading = true;
      this.databaseMsg =
        "<span style='color: #333333;font-size: 12px;'>尝试连接数据库…</span>";
      connectToDatabase(this.form)
        .then(async (res) => {
          this.databaseMsg =
            "<span style='color: #52C41A;font-size: 12px;'>连接成功</span>";
          this.btnLoading = false;
          // 连成功-获取表
          this.retrieveTableNames();
        })
        .catch((err) => {
          this.btnLoading = false;
          this.databaseMsg =
            "<span style='color: #FF4D4F;font-size: 12px;'>连接失败。连接成功后编辑后期配置</span>";
          console.log(err, "连接数据库失败");
        });
    },
    // 获取表
    async retrieveTableNames() {
      const tab = await retrieveTableNames(this.form);
      console.log(tab, "连接数据库-获取表");
      const { data } = tab;
      this.tabNames = data;
    },
    // 添加流并获取流下的属性
    streamSele(val) {
      listAttributes({
        siddhiAppName: this.form.siddhiAppName,
        streamName: this.form.streamName,
      }).then((res) => {
        const { data } = res;

        this.form.listAttributes = data.map((item) => {
          return {
            ...item,
            isCheck: false,
            value: "",
            type: [item.type],
            attributesType: "", //当前选中属性 类型下拉
          };
        });
      });
    },
    // 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组，如不传则移除整个表单的校验结果
    clearValidate(fromName) {
      this.$nextTick(() => {
        this.$refs["formName"].clearValidate(fromName);
      });
    },
    // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
    resetFields() {
      this.$nextTick(() => {
        // this.form.listAttributes = [];
        this.form = this.$options.data().form;
        this.tabNames = [];
        this.attributesTypeSele = [];
        this.$refs["formName"].resetFields();
      });
    },
    // 提交
    onSubmit() {
      this.$refs["formName"].validate((valid) => {
        if (valid) {
          this.form.columnNamesList = this.form.listAttributes.join(",");
          this.form.isTimestampInterval == true
            ? (this.form.timestampAttribute = "")
            : (this.form.timestampInterval = "");
          this.form.attributeConfList = [_.cloneDeep(this.form)];
          this.$emit("onSubmit", this.form);
          this.resetFields();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //删除
    handleDel() {
      this.$emit("handleDelSiddhiType", this.form);
    },
    // 获取流
    siddhiSele(val) {
      listStreams(val).then((res) => {
        const { data } = res;
        this.form.listStreams = data.map((item) => {
          return {
            name: item,
          };
        });
      });
    },
  },
};
</script>


<style scoped lang='scss'>
.connect_msg {
  display: flex;
  align-items: center;
}
.btns {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  /* padding: 0 30px; */
  position: absolute;
  bottom: 30px;
  right: 20px;
  width: 100%;
}
.mu_box {
  height: calc(100vh - 160px);
  overflow: auto;
  border-bottom: 1px solid #e4e4e4;
  padding: 0 20px;
  padding-bottom: 30px;
  .user_paw {
    display: flex;
    justify-content: space-between;
  }
  /deep/ .el-form-item {
    margin-bottom: 0;
    .el-form-item__label {
      padding: 0;
      width: 100% !important;
    }
  }
}
</style>